package com.fm.jbsql.entry;

import com.fm.jbsql.util.CmdOpt;
import com.fm.jbsql.util.JbsqlException;

import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Vector;
import java.io.*;

/**
 * Created by IntelliJ IDEA.
 * User: syaroshenko
 * Date: Jul 13, 2006
 * Time: 11:36:27 AM
 * Class to manage sql.lst.
 */

/**
 * Class to manage sql.lst.
 */
final class ProjectSQL extends Project {
    private static final Logger logger = Logger.getLogger("com.fm.jbsql.entry.ProjectSQL");

    /**
     * Constructor.
     * @param _cmdopt command line arguments
     */
    ProjectSQL(final CmdOpt _cmdopt) {
        super.setCmdOpt(_cmdopt);
    }

    /**
     * Parse entries.
     * @param f File
     * @param v Vector of resulting entries
     * @param bSrcShouldExist flag to throw error unless entries source exists
     * @param isGetRevisionMode mode to retrieve revision of pushed files only
     * @param inputFiles pushed files to retrieve revision
     * @throws NullPointerException
     * @throws JbsqlException
     */
    void parseEntries(File f, Vector v, boolean bSrcShouldExist, boolean isGetRevisionMode, String []inputFiles) throws NullPointerException, JbsqlException {
        logger.log(Level.FINE, "start");
        super.parseEntries(f, v, bSrcShouldExist, isGetRevisionMode, inputFiles);

        String s;
        try {
            BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF8"));
            while ( (s=is.readLine()) != null ) {
                s = s.trim();
                if ( s.length() == 0 ) continue;
                if ( s.charAt(0) != '#' ) v.add(new Entry(s, ""));
            }
            is.close();
        }
        catch (FileNotFoundException ex) {
            if ( bSrcShouldExist ) {
                throw new JbsqlException("FNF_01", f.getName(), ex);
            }
            else logger.info("No entries source found, skipping.");
        }
        catch (IOException ex) {
            throw new JbsqlException("IOE_04", f.getName(), ex);
        }
        logger.log(Level.FINE, "finish");
    }

    /**
     * Verify if listed files physically exist.
     * @throws JbsqlException
     */
    public void verifyEntrySourceIntegrity() throws JbsqlException {
        logger.log(Level.FINE, "start");

        Vector entries = new Vector();
        parseEntries(cmdopt.getEntriesSource(), entries, true, false, null);

        File f;
        for ( int loop = 0; loop < entries.size(); loop++ ) {
            f = new File(((Entry)entries.get(loop)).name.replace('\\', File.separator.toCharArray()[0]));
            if ( !f.exists() ) {
                throw new JbsqlException("FNF_01", ((Entry)(entries.get(loop))).name.replace('\\', File.separator.toCharArray()[0]), null);
            }
        }
        logger.log(Level.FINE, "finish");
    }
}

